# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '138989': {  # witch qq1.8%（10---1000），支付宝3.6%（10---3000）。d0结算。
        'API_KEY': 'IWSVxuKkxt1527651029OV1dnLulzSq',
        'src_code': 'XFZFyZ401527651029ZyryM',
        'gateway': 'http://api.xinfuokpay.com/trade/pay',
        'query_gateway': 'http://api.xinfuokpay.com/trade/query',
    },
    '139013': {  # loki 支付宝3.6%（10---3000）。d0结算。
        'API_KEY': 'uw2Xhinwpy1530586197ivBJlpCMk2n',
        'src_code': 'XFZFunMF1530586197yZ2gA',
        'gateway': 'http://api.xinfuokpay.com/trade/pay',
        'query_gateway': 'http://api.xinfuokpay.com/trade/query',
    },
    '139014': {  # dwc 支付宝3.6%（10---3000）。d0结算。
        'API_KEY': '4hqb4dZxp41530586580GPUHJblXpc4',
        'src_code': 'XFZFkwC41530586580AF3xC',
        'gateway': 'http://api.xinfuokpay.com/trade/pay',
        'query_gateway': 'http://api.xinfuokpay.com/trade/query',
    },
    '145752': {  # dwc 支付宝3.3%（100---5000）D0结算
        'API_KEY': 'DSWa0aImvi1536119720jFVuFUkR3oO',
        'src_code': 'XFGznE1536119720BCAmj',
        'gateway': 'http://api.xfzfvip.com/trade/pay',
        'query_gateway': 'http://api.xfzfvip.com/trade/query',
    },
    '145750': {  # witch 支付宝3.3%（20---5000）D0结算
        'API_KEY': 'zmj2oZygaK1536119290n3LnJ68RqfX',
        'src_code': 'XFls3h1536119290SK3ch',
        'gateway': 'http://api.xfzfvip.com/trade/pay',
        'query_gateway': 'http://api.xfzfvip.com/trade/query',
    },
    '145751': {  # loki 支付宝3.3%（20---5000）D0结算
        'API_KEY': 'IVpIYzZtod1536119610Ob77bf8wChs',
        'src_code': 'XFgeHl1536119610hsTKU',
        'gateway': 'http://api.xfzfvip.com/trade/pay',
        'query_gateway': 'http://api.xfzfvip.com/trade/query',
    },
    '145764': {
        # dwc 支付宝3%（20---5000）D0结算
        # dwc 快捷收银台 1.5% 1-3000
        'API_KEY': 'FZWatiYnpj1538642777eCGXLYx0mO0',
        'src_code': 'XFrp8H1538642777cLQvQ',
        'gateway': 'http://api.xfzfvip.com/trade/pay',
        'query_gateway': 'http://api.xfzfvip.com/trade/query',
    },
    '145763': {
        # witch 支付宝3%（20---5000）D0结算
        # witch 快捷收银台 1.5% 1-3000
        'API_KEY': 'I7Z4nV4tev1538642621M0bOEPnduSO',
        'src_code': 'XFdXeJ1538642621uqnmW',
        'gateway': 'http://api.xfzfvip.com/trade/pay',
        'query_gateway': 'http://api.xfzfvip.com/trade/query',
    },
    '145765': {
        # loki 支付宝3%（20---5000）D0结算
        # loki 快捷收银台 1.5% 1-3000
        'API_KEY': 'POILaDcFpv1538642869qniLEFiDzNU',
        'src_code': 'XF6QUF1538642869l3xQN',
        'gateway': 'http://api.xfzfvip.com/trade/pay',
        'query_gateway': 'http://api.xfzfvip.com/trade/query',
    },
    '145800': {
        # tt 支付宝 2.8%（50-5000）
        # tt 快捷收银台 1.5% 1-3000
        'API_KEY': 'g6Kzp8GrMp1545645011pdnqwG2Qt8N',
        'src_code': 'XFaRF11545645011dpzdz',
        'gateway': 'http://api.xfzfvip.com/trade/pay',
        'query_gateway': 'http://api.xfzfvip.com/trade/query',
    },
    '148739': {
        # loki 支付宝H5 3%（10-5000）
        'API_KEY': 'BRPyUK34mB1548752127sMrw170lG1a',
        'src_code': 'NXF1jcV1548752127YLHO8',
        'gateway': 'http://api.xfzfvip.com/trade/pay',
        'query_gateway': 'http://api.xfzfvip.com/trade/query',
    },
    '148738': {
        # witch 支付宝H5 3%（10-5000）
        'API_KEY': '0pRqCpFBQf1548751487KsEqQ0dGcuF',
        'src_code': 'NXFvCMZ1548751487mHKdH',
        'gateway': 'http://api.xfzfvip.com/trade/pay',
        'query_gateway': 'http://api.xfzfvip.com/trade/query',
    },
    '148737': {
        # dwc 支付宝H5 3%（10-5000）
        'API_KEY': '6ERrtj34WN1548751319Ueu76wULHQh',
        'src_code': 'NXFtNSN1548751319ULxCf',
        'gateway': 'http://api.xfzfvip.com/trade/pay',
        'query_gateway': 'http://api.xfzfvip.com/trade/query',
    },
    '148740': {
        # zs 支付宝H5 3%（10-5000）
        'API_KEY': 'BzizY9lJFj1548752873irAwT3zyBoC',
        'src_code': 'NXFv84W1548752873mDI6E',
        'gateway': 'http://api.xfzfvip.com/trade/pay',
        'query_gateway': 'http://api.xfzfvip.com/trade/query',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_src_code(mch_id):
    return APP_CONF[mch_id]['src_code']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if k != 'sign' and parameter[k] != '':
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    print s
    _LOGGER.info("xinpay sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("xinpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# 交易类型，
# 银联二维码:30104;
# QQ 钱包扫码:40104;
# QQ 钱包 wap:40107;
# 微信刷卡:50101;
# 微信 APP:50102;
# 微信公众号:50103;
# 微信扫码:50104;
# 微信wap:50107;
# 微信wap扫码:50204;
# 支付宝反扫:60101;
# 支付宝 APP:60102;
# 支付宝服务窗:60103;
# 支付宝扫码:60104;
# 支付宝 H5/wap:60107;
# 网关支付:80103;
# 收银台:80101;
# 翼支付:91101;
# 京东扫码:92104;
# 百度扫码:93104;
# 苏宁扫码:94104;
# 快捷交易:70103
# 快捷收银台:70101
def _get_pay_type(service):
    if service == 'wxpay':
        return '50107'
    elif service == 'alipay':
        return '60107'
    elif service == 'qq':
        return '40107'
    elif service == 'quick':
        return '70103'
    elif service == 'union_pay_quick':
        return '70101'
    else:
        return '92104'
    return payType


# 支持微信 qq 网关 支付宝
def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('src_code', _get_src_code(app_id)),
        ('out_trade_no', str(pay.id)),
        ('total_fee', str(int(pay_amount * 100))),
        ('time_start', local_now().strftime("%Y%m%d%H%M%S")),
        ('goods_name', 'charge'),
        ('trade_type', _get_pay_type(service)),
        ('finish_url', '{}/pay/api/{}/xinpay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('mchid', app_id),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("xinpay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['out_trade_no'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("xinpay create charge data: %s %s", response.status_code, response.text)
    return {'charge_info': json.loads(response.text)['data']['pay_params']}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("xinpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['out_trade_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('xinpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['order_status'])
    trade_no = data['trade_no']
    total_fee = float(data['total_fee']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '3':
        _LOGGER.info('xinpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('src_code', _get_src_code(app_id)),
        ('out_trade_no', str(pay_order.id)),
        ('mchid', app_id),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info('xinpay query data, %s', parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info('xinpay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)['data'][0]
        mch_id = pay_order.mch_id
        trade_status = str(data['order_status'])
        total_fee = float(data['total_fee']) / 100.0
        trade_no = data['trade_no']

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        # → 1:下单中;2:等待支付;3:支付成功;4:支付失 败;6:用户未支付
        if trade_status == '3':
            _LOGGER.info('xinpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
